package com.examples.springboot.jpa.gui.department;

import java.awt.Color;
import java.awt.Component;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;

import javax.swing.AbstractCellEditor;
import javax.swing.JComboBox;
import javax.swing.JTable;
import javax.swing.table.TableCellEditor;

import com.examples.springboot.jpa.pojos.DepartmentDto;
import com.examples.springboot.jpa.resources.DepartmentResource;

/**
 * A custom editor for cells in the Mount column.
 *
 */
@SuppressWarnings("serial")
public class DepartmentCellEditor extends AbstractCellEditor 
		implements TableCellEditor, ActionListener {

	private DepartmentDto selectedDepartments;
	private Iterable<DepartmentDto> departments;
	private PropertyChangeListener listener;
	private int mSelectRowNumber;

	private final DepartmentResource mResource;
	public DepartmentCellEditor(DepartmentResource resource,PropertyChangeListener listener) {
	  this.listener=listener;
		this.mResource=resource;
	}

	@Override
	public Object getCellEditorValue() {
		return this.selectedDepartments;
	}

	public void loadData() {
	  setData(mResource.getAll()
	  );
  }

	public void setData(Iterable<DepartmentDto> departments) {
	  this.departments=departments;
  }

	@Override
	public Component getTableCellEditorComponent(JTable table, Object value,
			boolean isSelected, int row, int column) {
	  if (value instanceof DepartmentDto) {
      this.selectedDepartments = (DepartmentDto) value;
    }

		JComboBox<DepartmentDto> comboMount = new JComboBox<>();

		for (DepartmentDto department : departments) {
			comboMount.addItem(department);
		}

		int indexOf = indexOf(selectedDepartments);
		comboMount.setSelectedIndex(indexOf);
		comboMount.addActionListener(this);
    comboMount.setBackground(Color.WHITE);
		
 		this.mSelectRowNumber=row;
		return comboMount;
	}

	public int getSelectRowNumber() {
    return mSelectRowNumber;
  }

	private int indexOf(DepartmentDto department) {
    int i = 0;
	  for (DepartmentDto item : departments) {
	    if(item.equals(department))
        return i;
      if(item.getName()!=null&&
          item.getName().equals(department.getName()))
        return i;
      i++;
    }

    return -1;
  }

	@Override
	@SuppressWarnings("unchecked")
	public void actionPerformed(ActionEvent event) {
    JComboBox<DepartmentDto> comboMount = (JComboBox<DepartmentDto>) event.getSource();
		listener.propertyChange(new PropertyChangeEvent(comboMount, "onDepartmentChanged", getCellEditorValue(), comboMount.getSelectedItem()));
    this.selectedDepartments = (DepartmentDto) comboMount.getSelectedItem();
	}

}
